class LazyImage {
    constructor(selector){
        this.imageElements = Array.prototype.slice.call(document.querySelectorAll(selector))
        this.init()
    }

    init(){
        // 通过IntersectionObserver api来判断图片是否出现在可视区域内，不需要监听scroll事件
        if ("IntersectionObserver" in window) {
            let lazyImageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach((entry, index)=>{
                    // 如果元素可见
                    if(entry.isIntersecting){
                        let lazyImage = entry.target
                        lazyImage.src = lazyImage.dataset.src
                        lazyImage.classList.remove("lazy-image")
                        lazyImageObserver.unobserve(lazyImage)
                        // this.lazyImages.splice(index, 1)
                    }
                })
            })

            this.imageElements.forEach(function(lazyImage){
                lazyImageObserver.observer(lazyImage)
            })
        } else {
            this.inViewShow()
            this._throttleFn = this.throttle(this.inViewShow)
            document.addEventListener("scroll", this._throttleFn)
        }
    }

    inViewShow(){
        let len = this.imageElements.length
        for(let i = 0; i<len; i++){
            let imageElement = this.imageElements[i]
            const rect = imageElement.getBoundingClientRect()
            // 出现在事业中
            if (rect.top < document.documentElement.clientHeight){
                imageElement.src = imageElement.dataset.src
                // 移除已经显示的
                this.imageElements.splice(i, 1)
                len--
                i--
                if(this.imageElements.length === 0){
                    // 如果全部加载完毕，则去除滚动事件监听
                    document.removeEventListener('scroll', this._throttleFn)
                }
            }
        }
    }
    // 节流函数
    throttle(fn, delay=15, mustRun=30){
        let t_start = null
        let timer = null
        let context = this
        return function(){
            let t_current = +(new Date())
            let args = Array.prototype.slice.call(arguments)
            clearTimeout(timer)
            if (!t_start){
                t_start = t_current
            }
            if (t_current - t_start > mustRun) {
                fn.apply(context, args)
                t_start = t_current
            } else {
                timer = setTimeout(()=>{
                    fn.apply(context, args)
                }, delay)
            }
        }
    }
}